<?php

/**
 * basket actions.
 *
 * @package    tsantek-shop
 * @subpackage basket
 * @author     Tomislav Šantek
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class basketActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
    public function executeIndex(sfWebRequest $request)
    {
        $this->baskets = BasketTable::getBaskets($this->getUser());

        if (!$this->baskets) return sfView::ERROR;

        $this->short_info = BasketTable::getShortInfo($this->baskets);
        $this->delivery_params = DeliveryCalculator::getNullDeliveryData();

        $dc = new DeliveryCalculator
        (
                array_merge
                (
                        array('baskets' => $this->baskets),
                        $this->delivery_params
                )
        );
        $this->calc = BasketTable::calculate($this->baskets, $dc, false, true);


    }

    public function executeAdd(sfWebRequest $request)
    {
        $this->forward404Unless($request->hasParameter('slug'));
        $slug = $request->getParameter('slug');
        $quantity = $request->getParameter('quantity', 1);

        $product = ProductTable::getInstance()->findOneBySlug($slug);

        if (!$product->getIsAvailable())
            $this->redirect('basket');

        $shop_id = $product->getShopId();

        $basket = BasketTable::getBasket($this->getUser(), $shop_id );
        BasketItemTable::insertItem($basket, $product, $quantity);

        $this->getUser()->setAttribute('last_product_category_slug', $product->getCategory()->getSlug());
        $this->redirect('basket');
    }

    public function executeRemoveitem(sfWebRequest $request)
    {
        BasketItemTable::removeItem($request->getParameter('item_id'), $this->getUser());

        if ($request->isXmlHttpRequest())
          return $this->renderComponent('basket','index');

        return $this->redirect('basket/index');
    }

    public function executeRemovebasket(sfWebRequest $request)
    {
        if(BasketTable::getBaskets($this->getUser())!=false)
            BasketTable::getBaskets($this->getUser())->delete();
        $this->redirect($request->getReferer());
    }

    public function executeChangequantity(sfWebRequest $request)
    {
        $quantity = $request->getParameter('quantity');
        $item_id = $request->getParameter('item_id');

        BasketItemTable::changeQuantity($item_id, $quantity, $this->getUser());
        if($request->isXmlHttpRequest())
            return $this->renderText ('ok');
        else
            $this->redirect ($this->generateUrl ('basket'));
    }
}
